package discovery

import (
	"time"

	"gitee.com/fanshuaiself/wss-gateway/pkg/nacos"
	"github.com/nacos-group/nacos-sdk-go/model"
)

type DiscoveryKernel struct {
	services map[string]model.Service
	intervalSeconds int 
	closeCh chan struct{}
}

func NewDiscovery() *DiscoveryKernel {
	return &DiscoveryKernel{
		services: make(map[string]model.Service),
		intervalSeconds: 30,
		closeCh: make(chan struct{}, 1),
	}
}

func (d *DiscoveryKernel) Start(globalCh chan struct{}) error {
	go d.doStart()
	return nil
}

func (d *DiscoveryKernel) doStart() {
	running := true
	for running {
		select {
		case <- d.closeCh:
			running = false
		case <- time.After(time.Duration(d.intervalSeconds) * time.Second):
			d.refreshServices()
		}
	}
}

func (d *DiscoveryKernel) refreshServices() {
	d.services = nacos.GetAllServices() 
}

func (d *DiscoveryKernel) Stop() {
	d.closeCh <- struct{}{}
}